import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import pojo.Person;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lemon
 * @version V1.0
 * @date 2020/08/31
 */
public class Demo5 {
    ObjectMapper mapper = new ObjectMapper();
    RestHighLevelClient client = ESClient.getClient();
    String index="person";
    String type="man";

    @Test
    public void createDoc() throws IOException{
        //1.准备一个json数据
        Person person = new Person(1,"张三",23,new Date());
        String json = mapper.writeValueAsString(person);

        //2.准备一个request对象(手动指定id)
        IndexRequest request = new IndexRequest(index,type,person.getId().toString());
        request.source(json, XContentType.JSON);

        //3.通过client对象执行添加
        IndexResponse resp = client.index(request, RequestOptions.DEFAULT);

        //4.输出返回结果
        System.out.println(resp.getResult().toString());
    }

    /**
     * 修改文档
     * @throws IOException
     */
    @Test
    public void updateDoc() throws IOException {
        //1.创建一个map,指定需要修改的内容
        Map<String,Object> doc = new HashMap<>();
        doc.put("name","张大三");
        String docId="1";

        //2.创建request对象，封装数据
        UpdateRequest request = new UpdateRequest(index,type,docId);
        request.doc(doc);

        //3.通过client对象执行
        UpdateResponse update = client.update(request,RequestOptions.DEFAULT);
        System.out.println(update.getResult().toString());
    }

    /**
     * 删除文档
     */
    @Test
    public void deleteDoc() throws IOException {
        //1.封装Request对象
        DeleteRequest request = new DeleteRequest(index,type,"1");

        //2.client执行
        DeleteResponse resp = client.delete(request,RequestOptions.DEFAULT);

        //3.输出结果
        System.out.println(resp.getResult().toString())  ;
    }
}
